﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Aliyun.OSS;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using zhangmenren.IService;
using zhangmenren.Models;
using zhangmenren.Untils;
using zhangmenren.Models.help;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;

namespace zhangmenren.Controllers
{
	[AllowAnonymous]
	public class LoginController : Controller
    {
        private IAdminService _adminService;
        private ICacheService _cacheService;
        private IUserService userService;

        public LoginController( IAdminService adminService, ICacheService cacheService,IUserService _userService)
        {
			_adminService = adminService;
            _cacheService = cacheService;
            userService = _userService;
        }
        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns>The index.</returns>
        public async Task<IActionResult> Index()
        {
			//AdminEntity admin = new AdminEntity();
			//admin.UserName = "admin";
			//admin.Pwd = FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5").ToLower(); "123456";
			//await _adminService.Add(admin);

			return View();
        }


        /// <summary>
        /// 登录
        /// </summary>
        /// <returns>The login.</returns>
        /// <param name="userName">User name.</param>
        /// <param name="pwd">Pwd.</param>
        public async Task< JsonResult> AjaxLogin(string mobile, string pwd)
        {
            var entity = await userService.FindMobile(mobile);

            if (entity==null)
            {
                return Json(new { state = "fail", msg = "用户不存在，请先注册" });
            }
            if (entity.Pwd!=Md5.MD5Str(pwd))
            {
                return Json(new { state = "fail", msg = "密码错误" });
            }

            UserCook cook = new UserCook();
            cook.Id = entity.Id;
            cook.Head = entity.Head;
            cook.UserName = entity.UserName;
            QTCookie.SaveCookie<UserCook>(Request.HttpContext, cook);

            return Json(new { state = "ok", msg = "登录成功" });

        }


        /// <summary>
        /// 注册页面
        /// </summary>
        /// <returns>The register.</returns>
        public IActionResult Register()
        {
            return View();
        }

		/// <summary>
		/// 忘记密码
		/// </summary>
		/// <returns>The get pwd.</returns>
		public IActionResult ForGetPwd()
        {
			//var aaa = Request.Cookies[CookieAuthenticationDefaults.AuthenticationScheme];
			return View();
        }

        public async Task<JsonResult> GetMobileCode(string mobile)
        {
            var user = await userService.FindMobile(mobile);
            if (user==null||string.IsNullOrEmpty(user.UserName))
            {
                return Json(new { state = "fail", msg = "手机号不存在。" });
            }
            return GetCode(mobile, "SMS_152090425");

        }

        /// <summary>
        /// 忘记密码并找回
        /// </summary>
        /// <returns>The pwd.</returns>
        /// <param name="mobile">Mobile.</param>
        /// <param name="code">Code.</param>
        /// <param name="pwd">Pwd.</param>
        [HttpPost]
        public async Task<JsonResult> SetPwd(string mobile,string code,string pwd)
        {
            var cd = _cacheService.Get<string>(mobile);
            if (cd != code)
            {
                return Json(new { state = "fail", msg = "验证码错误，请重新输入!" });
            }
            _cacheService.Remove(mobile);
            if (string.IsNullOrEmpty(pwd))
            {
                return Json(new { state = "fail", msg = "密码不能为空!" });
            }

            var result = await userService.SetPwd(Md5.MD5Str(pwd),mobile);
            return Json(new { state = "ok", msg = "修改成功，请登录!" });

        }

        /// <summary>
        /// 注册获取手机验证码
        /// </summary>
        /// <returns>The code.</returns>
        /// <param name="mobile">Mobile.</param>
        public async Task<JsonResult> MobileCode(string mobile)
        {
            var user = await userService.FindMobile(mobile);
            if (user!= null && !string.IsNullOrEmpty(user.UserName))
            {
                return Json(new { state = "fail", msg = "手机号已存在。" });
            }
            return GetCode(mobile, "SMS_152090426");

        }

        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <returns>The code.</returns>
        /// <param name="mobile">Mobile.</param>
        public JsonResult GetCode(string mobile,string type)
        {
            if (_cacheService.Exists(mobile))
            {
                return Json(new { state = "fail", msg = "发送验证码的有效期为30分钟，前一个验证码还在有效期。" });
            }

            var code= RandomHelper.GenerateRandomCode(6);

            var send = AliSMS.SendSMS(mobile, code, type);

            if (send)
            {
                _cacheService.Add(mobile, code, TimeSpan.FromMinutes(30), false);
                return Json(new { state = "ok", msg = "发送成功" });
            }
            return Json(new { state = "fail", msg = "发送失败请联系我们解决" });

        }

        /// <summary>
        /// 微信登录
        /// </summary>
        /// <returns>The code.</returns>
        public async Task< JsonResult> WeChat(string openId,string userName,string head)
        {
            var entity = await userService.FindOpenId(openId);


            if (entity==null|| entity.Id==0||string.IsNullOrEmpty(entity.UserName))
            {

                UserEntity user = new UserEntity();
                user.Head = head;
                user.UserName = userName;
                user.OpenId = openId;

                var result = await userService.AddWeiXin(user);
                entity = await userService.FindOpenId(openId);

            }

            UserCook cook = new UserCook();
            cook.Id = entity.Id;
            cook.Head = entity.Head;
            cook.UserName = entity.UserName;
            QTCookie.SaveCookie<UserCook>(Request.HttpContext, cook);

            return Json(new { state = "ok", msg = "登录成功" });

        }


        public async Task<JsonResult> QQ(string qq, string userName, string head)
        {
            var entity = await userService.FindOpenId(qq);
            if (entity.Equals(new UserEntity()))
            {
                UserEntity user = new UserEntity();
                user.Head = head;
                user.UserName = userName;
                user.QQId = qq;
                var result = await userService.Add(user);
                entity = await userService.FindOpenId(qq);
            }

            UserCook cook = new UserCook();
            cook.Id = entity.Id;
            cook.Head = entity.Head;
            cook.UserName = entity.UserName;

            Response.Cookies.Append(Config.USERCOOK, JsonConvert.SerializeObject(cook));

            return Json(new { state = "ok", msg = "登录成功" });

        }



        [HttpPost]
        public async Task<JsonResult> Register(string name,string pwd,string mobile,string code)
        {
            var cd = _cacheService.Get<string>(mobile);
            if (cd!=code)
            {
                return Json(new { state = "fail", msg = "验证码错误，请重新输入!" });
            }
            if (string.IsNullOrEmpty(name))
            {
                return Json(new { state = "fail", msg = "请输入用户名!" });
            }

            if (string.IsNullOrEmpty(pwd))
            {
                return Json(new { state = "fail", msg = "密码不能为空!" });
            }


            var entity = await userService.Find(name);

            if (!entity.Equals(new UserEntity()))
            {
                return Json(new { state = "fail", msg = "用户名已存在！" });
            }

            entity.Mobile = mobile;
            entity.Pwd = Md5.MD5Str(pwd);
            entity.UserName = name;
           var result=await userService.Add(entity);

            return Json(new { state = "ok", msg = "注册成功" });
        }



        [HttpPost]
        public JsonResult UploadFilesAjax()
        {
            var files =HttpContext.Request.Form.Files;
            List<string> list = new List<string>();
            foreach (var file in files)
            {
                var type = UpLoadHelper.GetExtension(file.FileName); //file.ContentType.Substring(file.ContentType.LastIndexOf('/') + 1);
                var filename = DateTime.Now.ToString("yyyyMMddHHmmss") + "." + type;
                var ossurl = Config.OSSURL;
                var endpoint = Config.ENDPOINT;
                var accessKeyId = Config.AccessKeyID;
                var accessKeySecret = Config.AccessKeySecret;
                var bucketName = Config.BACKETNAME;
                var objectName = filename;
                var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
                try
                {
                    var result = client.PutObject(bucketName, objectName, file.OpenReadStream());
                    list.Add(ossurl + objectName);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Put object failed, {0}", ex.Message);
                }
            }
            return Json(new { code = 0, msg = "上传成功", data = new { src = string.Join(",", list.ToArray()) } });
        }




    }
}
